package net.zhongfu.flowable.helper.common.configuration;

import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Description: 配置flowable数据库变化工具,默认不开启
 * @Author: fsrong
 * @Date: 2021/7/13 16:04
 */
@Configuration
@ConditionalOnProperty(name = "liquibase.act-de.enable",havingValue = "true",matchIfMissing = true)
public class DefaultLiquibase {
    private static final Logger logger = LoggerFactory.getLogger(DefaultLiquibase.class);

    protected static final String LIQUIBASE_CHANGELOG_PREFIX = "ACT_DE_";



    /**
     * @Description: ACT_DE的包无法生成,使用如下的配置类
     * @param dataSource 数据源
     * @Author: fsrong
     * @Date: 2021/7/13 16:02
     */
    @Bean("liquibaseActDe")
    public Liquibase liquibase(@Autowired DataSource dataSource) throws LiquibaseException {
        logger.info("Liquibase 配置生成{}为前缀的相关表",LIQUIBASE_CHANGELOG_PREFIX);
        Liquibase liquibase = null;
        try {
            DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
            database.setDatabaseChangeLogTableName(LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName());
            database.setDatabaseChangeLogLockTableName(LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName());
            liquibase = new Liquibase("META-INF/liquibase/flowable-modeler-app-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
            liquibase.update("flowable");
            return liquibase;
        } catch (Exception e) {
            throw new LiquibaseException("Flowable适配数据库，Creating Liquibase Database Error", e);
        } finally {
            closeDatabase(liquibase);
        }
    }


    private void closeDatabase(Liquibase liquibase) {
        if (liquibase != null) {
            Database database = liquibase.getDatabase();
            if (database != null) {
                try {
                    database.close();
                } catch (DatabaseException e) {
                    logger.warn("Error closing database", e);
                }
            }
        }
    }
}
